package logic

import (
	"context"

	"googee/common/errorx"
	"googee/common/tool"
	"googee/service/captcha/rpc/captcha"
	"googee/service/user/api/internal/svc"
	"googee/service/user/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type SendimgcodeLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSendimgcodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendimgcodeLogic {
	return &SendimgcodeLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SendimgcodeLogic) Sendimgcode(req *types.BindPhoneImgCodeReq) (resp *types.BindPhoneImgCodeReply, err error) {
	resp = &types.BindPhoneImgCodeReply{}

	phone := req.Phone

	if !tool.VerifyMobileFormat(phone) {
		return nil, errorx.NewCodeErrorNoMsg(errorx.USER_ERROR + 4)
	}

	result, err := l.svcCtx.Captcha.Gen(l.ctx, &captcha.GenRequest{Key: phone})
	if err != nil {
		st, ok := status.FromError(err)
		if ok {
			if st.Code() == codes.InvalidArgument {
				return nil, errorx.NewCodeErrorNoMsg(errorx.USER_ERROR + 4)
			} else if st.Code() == codes.Internal {
				return nil, errorx.NewCodeError(errorx.INTERNAL_ERROR, "系统内部未知错误")
			}
		} else {
			return nil, errorx.NewCodeError(errorx.INTERNAL_ERROR, "系统内部未知错误")
		}
	}

	resp.Data.Captcha = result.ImgBase64
	return
}
